package com.yj.suncity.user;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import com.yj.suncity.R;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.publish.PublishAdvertiseActivity;
import com.yj.suncity.user.bean.EntBean;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.HttpUtil;
import com.yj.suncity.utis.ProgressUtil;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.UploadUtil;
import com.yj.suncity.utis.DialogUtils.ItemCall;
import com.yj.suncity.utis.UploadUtil.OnUploadProcessListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class UpdateShopInfoActivity extends Activity implements OnClickListener {

	private final int PIC_FROM_CAMERA = 101;
	private final int PIC_FROM＿LOCALPHOTO = 102;
	private static final int FAIL = 1;
	private static final int SUCCESS = 2;
	private static final int IO_EXCEPTION = 3;
	private static final int JSON_EXCEPTION = 4;
	private Context context;
	private String userId;
	private String entId;// 企业id
	private ImageView mImg_user_logo;
	private String uploadHead = "";
	private String user_head_img = "";
	private DisplayImageOptions options;
	private ArrayList<String> listImg = new ArrayList();
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private List<NameValuePair> pairs = new ArrayList<NameValuePair>();
	private SharedPreferencesUtil preferencesUtil = SharedPreferencesUtil
			.getInstance();
	private String cateName = "";
	private String cateId = "";
	private TextView mTxt_cate_name;
	private EditText mEdt_ent_name, mEdt_ent_username, mEdt_id_card;
	private EditText mEdt_contact_name, mEdt_contact_type,
			mEdt_contact_address;
	private EditText mEdt_business_license, mEdt_organization_code;
	private EditText mEdt_ent_jianjie, mEdt_ent_link;
	private ProgressUtil progressUtil;
	private String titleName;
	private int flag;// 1,修改资料
	private TextView mTxt_hint;
	private TextView mTxt_img_hint;
	private String shopImgs;

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FAIL:
				progressUtil.ShowProgress(context, false, false, "正在修改......");
				ToastUtil.ShowToast(context, "" + (String) msg.obj);
				break;
			case SUCCESS:
				progressUtil.ShowProgress(context, false, false, "正在修改......");
				ToastUtil.ShowToast(context, "修改成功！");
				UpdateShopInfoActivity.this.finish();
				break;
			case IO_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在修改......");
				ToastUtil.ShowToast(context, "网络异常！");
				break;
			case JSON_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在修改......");
				ToastUtil.ShowToast(context, "数据解析异常！");
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update_shop_info);
		context = this;
		userId = getIntent().getStringExtra("userid");
		entId = getIntent().getStringExtra("entid");
		titleName = getIntent().getStringExtra("titlename");
		flag = getIntent().getIntExtra("flag", -1);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		findView();
		initData();
	}

	private void findView() {
		((TextView) findViewById(R.id.txt_title_name)).setText(titleName);
		mTxt_hint = (TextView) findViewById(R.id.txt_hint);
		mTxt_img_hint = (TextView)findViewById(R.id.txt_img_hint);
		mImg_user_logo = (ImageView) findViewById(R.id.img_user_logo);
		mImg_user_logo.setOnClickListener(this);
		mTxt_cate_name = (TextView) findViewById(R.id.txt_cate_name);
		mTxt_cate_name.setOnClickListener(this);

		mEdt_ent_name = (EditText) findViewById(R.id.edt_entname);
		mEdt_ent_username = (EditText) findViewById(R.id.edt_ent_username);
		mEdt_id_card = (EditText) findViewById(R.id.edt_id_card);

		mEdt_contact_name = (EditText) findViewById(R.id.edt_contact_name);
		mEdt_contact_type = (EditText) findViewById(R.id.edt_contact_type);
		mEdt_contact_address = (EditText) findViewById(R.id.edt_contact_address);

		mEdt_business_license = (EditText) findViewById(R.id.edt_business_license);
		mEdt_organization_code = (EditText) findViewById(R.id.edt_organization_code);

		mEdt_ent_jianjie = (EditText) findViewById(R.id.edt_ent_jianjie);
		mEdt_ent_link = (EditText) findViewById(R.id.edt_ent_link);

		if (flag == 1) {// 修改资料
			mEdt_ent_name.setEnabled(false);
			mEdt_ent_name.setClickable(false);

			mTxt_cate_name.setClickable(false);
			mTxt_cate_name.setEnabled(false);

			mEdt_ent_username.setEnabled(false);
			mEdt_ent_username.setClickable(false);

			mEdt_id_card.setEnabled(false);
			mEdt_id_card.setClickable(false);

			mEdt_business_license.setEnabled(false);
			mEdt_business_license.setClickable(false);

			mEdt_organization_code.setEnabled(false);
			mEdt_organization_code.setClickable(false);

//			mEdt_ent_jianjie.setEnabled(false);
//			mEdt_ent_jianjie.setClickable(false);
//
//			mEdt_ent_link.setEnabled(false);
//			mEdt_ent_link.setClickable(false);

			mTxt_hint.setVisibility(View.GONE);
		} else {// 补充资料
			mTxt_hint.setVisibility(View.VISIBLE);
		}
	}

	private void initData() {
		String path = URLCon.用户 + "?action=getentinfobyentid&entid=" + entId;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, false, "正在加载......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						EntBean entBean = new EntBean(jsonObject);
						if (entBean.getSuccess().equals("1")) {
							
							shopImgs = entBean.getImg();
							if(!"".equals(shopImgs)){
								if (!UpdateShopInfoActivity.this.shopImgs.contains(",")){
									listImg.add(shopImgs);
								}else{
									String[] date = shopImgs.split(",");
									for(int i = 0;i < date.length;i++){
										listImg.add(date[i]);
									}
								}
							}
							mTxt_img_hint.setHint("共" + listImg.size() + "张图片介绍，点击修改");
							user_head_img = entBean.getEnt_logo();
							imageLoader.displayImage(URLCon.HOST
									+ user_head_img, mImg_user_logo, options);
							cateId = entBean.getTradeid();
							cateName = entBean.getTradename();
							mTxt_cate_name.setText(cateName);
							mEdt_ent_name.setText(entBean.getEntname());
							mEdt_ent_username.setText(entBean.getLegal_person());
							mEdt_id_card.setText(entBean.getLegal_idcard());
							mEdt_contact_name.setText(entBean.getEnt_contact());
							mEdt_contact_type.setText(entBean
									.getEnt_contact_tel());
							mEdt_contact_address.setText(entBean
									.getEnt_address());

							mEdt_business_license.setText(entBean
									.getEnt_license());
							mEdt_organization_code.setText(entBean
									.getEnt_code());

							mEdt_ent_link.setText(entBean.getEnt_weblink());
							mEdt_ent_jianjie.setText(entBean.getEnt_jianjie());

							if (entBean.getEntname().equals("")) {// 商户名
								mEdt_ent_name.setEnabled(true);
								mEdt_ent_name.setClickable(true);
							}
							if (entBean.getLegal_person().equals("")) {// 法人
								mEdt_ent_username.setEnabled(true);
								mEdt_ent_username.setClickable(true);
							}
							if (entBean.getLegal_idcard().equals("")) {// 法人证件
								mEdt_id_card.setEnabled(true);
								mEdt_id_card.setClickable(true);
							}
							if (entBean.getEnt_license().equals("")) {// 营业执照
								mEdt_business_license.setEnabled(true);
								mEdt_business_license.setClickable(true);
							}
							if (entBean.getEnt_code().equals("")) {// 组织结构代码
								mEdt_organization_code.setEnabled(true);
								mEdt_organization_code.setClickable(true);
							}
							if (entBean.getEnt_jianjie().equals("")) {// 简介
								mEdt_ent_jianjie.setEnabled(true);
								mEdt_ent_jianjie.setClickable(true);
							}
							if (entBean.getEnt_weblink().equals("")) {// 行业
								mEdt_ent_link.setEnabled(true);
								mEdt_ent_link.setClickable(true);
							}
							if (cateName.equals("")) {// 行业
								mTxt_cate_name.setEnabled(true);
								mTxt_cate_name.setClickable(true);
							}

						} else {
							ToastUtil.ShowToast(context, entBean.getMsg());
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.img_user_logo:
			popView();
			break;
		case R.id.lay_rela_show_pic:
			Intent localIntent = new Intent(this.context, ShopImgsActivity.class);
	        localIntent.putStringArrayListExtra("paths", this.listImg);
	        localIntent.putExtra("entid", this.entId);
	        startActivityForResult(localIntent, 1001);
			break;
		case R.id.txt_cate_name:// 选择行业类型
			startActivityForResult(new Intent(this, ShopCateActivity.class),
					102);
			break;
		case R.id.btn_ok:

			Log.d("", "uploadHead==" + uploadHead);
			progressUtil = new ProgressUtil();

			if (uploadHead.equals("")) {
				uploadHead = user_head_img;
				if (!setPairs())
					return;
				progressUtil.ShowProgress(context, true, false, "正在修改......");
				updateInfo();

			} else {
				if (!setPairs())
					return;

				progressUtil.ShowProgress(context, true, false, "正在修改......");

				Map<String, String> param = new LinkedHashMap<String, String>();
				List<String> filePaths = new ArrayList<String>();
				filePaths.add(uploadHead);
				param.put("action", "uploads");
				UploadUtil uploadUtil = new UploadUtil();
				uploadUtil.uploadFile(context, filePaths, "txtimg",
						URLCon.图片上传, param, new OnUploadProcessListener() {

							@Override
							public void UploadResule(String result) {
								Log.d("", "result===" + result);
								// {"success":"1","msg":"ä¸ä¼ æå","data":[{"url":
								// "/upload/201504/15/201504151021483780.jpg"}]}

								try {
									JSONObject jsonObject = new JSONObject(
											result);
									if (jsonObject.optString("success").equals(
											"1")) {
										JSONArray array = jsonObject
												.optJSONArray("data");
										JSONObject item = array
												.optJSONObject(0);
										uploadHead = item.optString("url");
										preferencesUtil.putString(context,
												ShareCon.USERFILE,
												ShareCon.USERLOGO, uploadHead);
										updateInfo();
									} else {
										Message message = new Message();
										message.what = FAIL;
										handler.sendMessage(message);
									}
								} catch (JSONException e) {
									Message message = new Message();
									message.what = JSON_EXCEPTION;
									handler.sendMessage(message);
									e.printStackTrace();
								}
							}
						});
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 设置请求参数发起请求
	 */
	private boolean setPairs() {
		String entname = mEdt_ent_name.getText().toString().trim();
		String entPerson = mEdt_ent_username.getText().toString().trim();
		String entIdCard = mEdt_id_card.getText().toString().trim();
		String contactName = mEdt_contact_name.getText().toString().trim();
		String contactType = mEdt_contact_type.getText().toString().trim();
		String contactAddress = mEdt_contact_address.getText().toString()
				.trim();

		String businessLicense = mEdt_business_license.getText().toString()
				.trim();
		String organizationCode = mEdt_organization_code.getText().toString()
				.trim();
		String entJianjie = mEdt_ent_jianjie.getText().toString().trim();
		String webLink = mEdt_ent_link.getText().toString().trim();
		if (uploadHead.equals("")) {
			ToastUtil.ShowToast(context, "请选择头像！");
			return false;
		}

		if (entname.equals("")) {
			ToastUtil.ShowToast(context, "请输入商户名称！");
			return false;
		}
		if (contactName.equals("")) {
			ToastUtil.ShowToast(context, "请输入联系人！");
			return false;
		}
		if (contactType.equals("")) {
			ToastUtil.ShowToast(context, "请输入联系方式！");
			return false;
		}
		if (contactAddress.equals("")) {
			ToastUtil.ShowToast(context, "请输入联系地址！");
			return false;
		}
		pairs.clear();
		pairs.add(new BasicNameValuePair("action", "modifyentinfo"));
		pairs.add(new BasicNameValuePair("id", entId));
		pairs.add(new BasicNameValuePair("entname", entname));
		pairs.add(new BasicNameValuePair("tradeid", cateId));
		pairs.add(new BasicNameValuePair("tradename", cateName));
		pairs.add(new BasicNameValuePair("entfr", entPerson));
		pairs.add(new BasicNameValuePair("fridcard", entIdCard));
		pairs.add(new BasicNameValuePair("entperson", contactName));
		pairs.add(new BasicNameValuePair("entphone", contactType));
		pairs.add(new BasicNameValuePair("entlicense", businessLicense));
		pairs.add(new BasicNameValuePair("entzzjgdm", organizationCode));
		pairs.add(new BasicNameValuePair("entaddress", contactAddress));
		pairs.add(new BasicNameValuePair("entjj", entJianjie));

		pairs.add(new BasicNameValuePair("isrenzheng", ""));
		pairs.add(new BasicNameValuePair("entjc", ""));
		pairs.add(new BasicNameValuePair("weblink", webLink));
		pairs.add(new BasicNameValuePair("remark", ""));
		return true;
	}

	private void updateInfo() {
		pairs.add(new BasicNameValuePair("entlogo", uploadHead));
		final String path = URLCon.用户;
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String json = HttpUtil.HttpClientdoPost(path, pairs);
					JSONObject jsonObject = new JSONObject(json);
					if (jsonObject.optString("success").equals("1")) {
						Message message = new Message();
						message.what = SUCCESS;
						handler.sendMessage(message);
					} else {
						Message message = new Message();
						message.what = FAIL;
						message.obj = jsonObject.optString("msg");
						handler.sendMessage(message);
					}
				} catch (IOException e) {
					Message message = new Message();
					message.what = IO_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				} catch (JSONException e) {
					Message message = new Message();
					message.what = JSON_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				}
			}
		});
		thread.start();
		thread = null;
	}

	// =============================================================================

	private void popView() {
		DialogUtils dialogUtils = DialogUtils.getInstance();
		dialogUtils.SelectPicDialog(context, new ItemCall() {
			@Override
			public void onIndexCall(int index) {
				if (index == 0) {
					doHandlerPhoto(PIC_FROM_CAMERA);
				} else {
					doHandlerPhoto(PIC_FROM＿LOCALPHOTO);
				}
			}
		});

	}

	/**
	 * 根据不同方式选择图片设置ImageView
	 * 
	 * @param type
	 *            0-本地相册选择，非0为拍照
	 */
	private Uri photoUri;// 需要上传的头像

	private void doHandlerPhoto(int type) {
		try {
			// 保存裁剪后的图片文件
			File pictureFileDir = new File(
					Environment.getExternalStorageDirectory(), "/upload");
			if (!pictureFileDir.exists()) {
				pictureFileDir.mkdirs();
			} else {
				File[] files = pictureFileDir.listFiles();
				if (files != null) {
					for (File file : files) {
						file.delete();
					}
				}
			}
			File picFile = new File(pictureFileDir, getPhotoFileName());
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri = Uri.fromFile(picFile);
			// photoUri = picFile.toString();
			if (type == PIC_FROM＿LOCALPHOTO) {
				Intent intent = getCropImageIntent();
				startActivityForResult(intent, PIC_FROM＿LOCALPHOTO);
			} else {
				Intent cameraIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
				startActivityForResult(cameraIntent, PIC_FROM_CAMERA);
			}

		} catch (Exception e) {
			Log.i("HandlerPicError", "处理图片出现错误");
		}
	}

	/**
	 * 调用本地图片剪辑程序
	 */
	public Intent getCropImageIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		setIntentParams(intent);
		return intent;
	}

	/**
	 * 启动相机裁剪程序
	 */
	private void cropImageUriByTakePhoto() {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		setIntentParams(intent);
		startActivityForResult(intent, PIC_FROM＿LOCALPHOTO);
	}

	/**
	 * 设置公用参数
	 */
	private void setIntentParams(Intent intent) {
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 600);
		intent.putExtra("outputY", 600);
		intent.putExtra("noFaceDetection", true); // no face detection
		intent.putExtra("scale", true);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
	}

	/**
	 * 用时间戳生成照片名称
	 * 
	 * @return
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'yyyyMMddHHmmss");
		return dateFormat.format(date) + ".jpg";
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PIC_FROM_CAMERA: // 拍照
			try {
				cropImageUriByTakePhoto();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case PIC_FROM＿LOCALPHOTO:
			try {
				if (photoUri != null) {
					Bitmap bitmap = BitmapFactory.decodeFile(photoUri
							.toString().replace("file://", ""));
					Log.d("", "bitmap=="+bitmap);
                    if (bitmap!=null) {
                    	uploadHead = photoUri.toString().replace("file://", "");
                    	imageLoader.displayImage("file://" + uploadHead,
                    			mImg_user_logo, options);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
		if (requestCode == 102 && resultCode == 102) {
			Log.d("",
					data.getStringExtra("catename") + "======="
							+ data.getStringExtra("cateid"));
			cateId = data.getStringExtra("cateid");
			cateName = data.getStringExtra("catename");
			mTxt_cate_name.setText(cateName);
		}
		if(requestCode == 1001 && resultCode == 1001) {
			this.listImg.clear();
	        this.shopImgs = data.getStringExtra("imgpaths");
	        if (!this.shopImgs.equals(""))
	        {
	          if (!this.shopImgs.contains(",")){	        	  
	        	  listImg.add(this.shopImgs);
	          }
	          String[] arrayOfString = this.shopImgs.split(",");
	          for(int i = 0;i < arrayOfString.length;i++){
	        	  listImg.add(arrayOfString[i]);
	          }
	        }
	        mTxt_img_hint.setHint("共" + data.getIntExtra("size", 0) + "张图片介绍，点击修改");
		}
	}

}
